package com.soup.lab.tools.mtt;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Date;
import java.util.concurrent.CountDownLatch;

public class MultiThreadTestUtils {

    private static final Logger logger = LoggerFactory.getLogger(MultiThreadTestUtils.class);

    public static void runAsync(String name, int threadCount, Runnable runnable) {
        Thread[] threads = new Thread[threadCount];
        for (int i = 0; i < threadCount; i++) {
            threads[i] = new Thread(runnable, name +"-"+ i);
            threads[i].start();
        }
    }

    public static void run(int threadCount, Runnable runnable) {
        run("test", threadCount, runnable);
    }

    public static void run(String name, int threadCount, Runnable runnable) {
        long start = System.currentTimeMillis();
        Thread[] threads = new Thread[threadCount];
        CountDownLatch overLatch = new CountDownLatch(threadCount);
        CountDownLatch startLatch = new CountDownLatch(1);
        for (int i = 0; i < threadCount; i++) {
            threads[i] = new Thread(() -> {
                try {
                    startLatch.await();
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                }
                long s = System.currentTimeMillis();
                boolean result = false;
                try {
                    logger.info("执行时间：{}", new Date());
                    runnable.run();
                    result = true;
                } finally {
                    logger.info("执行：{}， 耗时：{} s", result ? "成功" : "异常", (System.currentTimeMillis() - s)/1000);
                    overLatch.countDown();
                }
            }, name +"-"+ i);
            threads[i].start();
        }
        startLatch.countDown();
        try {
            overLatch.await();
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }
        logger.info("总耗时：{} s", (System.currentTimeMillis() - start)/1000);
    }

}
